package cn.yunhe.insurance.controller;


import cn.yunhe.insurance.entity.*;
import cn.yunhe.insurance.service.ComboService;
import cn.yunhe.insurance.service.InsurcateService;
import cn.yunhe.insurance.service.OrderService;
import cn.yunhe.insurance.util.DateUtil;
import cn.yunhe.insurance.util.OrderParam;
import cn.yunhe.insurance.util.Result;
import cn.yunhe.insurance.util.UUIDGenerator;

import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author 苏文秀
 * @date 2018/9/15 10:01
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    /////添加日志
    private static final Logger log=LoggerFactory.getLogger(OrderController.class);
    @Resource
    private OrderService orderService;
    @Resource
    private ComboService comboService;
    @Autowired
    private InsurcateService insurcateService;


    Result result = new Result();
    @RequestMapping("/toOrderQuery")
    public ModelAndView toQueryOrder() {
        return new ModelAndView("orderQuery");
    }

    @RequestMapping("/queryOrderPage")
    public Map<String, Object> queryOrderPage(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                                              @RequestParam(value = "pageSize",defaultValue = "8") Integer pageSize,
                                              String keyword,Integer paystate,Integer ostate) {

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("pageNum",pageNum);
        map.put("pageSize",pageSize);
        if (keyword.equals("")||keyword==null){
            keyword=null;
        }
        map.put("keyword",keyword);
        map.put("paystate",paystate);
        map.put("ostate",ostate);
        Page<Order> page=orderService.getOrderPage(map);
        map.put("page",page);
        map.put("totalPages",page.getPages());
        return map;

    }

    ///////跳转到 购买保险页面
    @RequestMapping("/toOrderInsurance")
    public ModelAndView toOrderInsurance() {
        return new ModelAndView("orderInsurance");
    }

    /////购买保险
    @RequestMapping("/buyInsurance")
    public boolean buyInsurance(Order order, String uid, String caruid, String comuuid, HttpSession session) {
        int count=orderService.getOrderByCar(caruid);
        if (count>0){
            return false;
        }
        order.setOuid(UUIDGenerator.getUUID());////订单uuid
        order.setOid(OrderParam.getOrderNum());//////生成保单
        order.setAddtime(DateUtil.date2StringDate(new Date()));////下单时间
        ////从session中获取当前登录的员工的信息
        Emp emp= (Emp) session.getAttribute("emp");
        order.setEmp(emp);

        User user=new User();
        user.setSuId(uid);
        order.setUser(user);

        Cars cars=new Cars();
        cars.setCarUuid(caruid);
        order.setCars(cars);

        Combo combo=new Combo();
        combo.setComuuid(comuuid);
        order.setCombo(combo);

        if (order.getPaystate()==1) {
            ////支付成功
            order.setOstate(0);
        }else{
            /////未支付
            order.setOstate(4);
        }
        boolean flag = orderService.addInsurance(order);
        return flag;
    }

    @RequestMapping("/getOrderByUserAndCars")
    public Result getOrderByUserAndCars(String licenseNum, String scardId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("licenseNum", licenseNum);
        map.put("scardId", scardId);
        Order order = orderService.getOrderByUserAndCars(map);
        if (order == null) {
            result.setCode(100001);////1001代表此客户还未购买过保险
            return result;
        } else {
            result.setCode(100002);////1002代表此用户购买过保险
            return result;
        }
    }

    @RequestMapping("/toGetDetails")
    public ModelAndView toGetDetails() {
        return new ModelAndView("orderDetails");
    }

    /**
     * 根据保单号 查询客户购买的保险的详细信息,并跳转页面
     * @param oid
     * @return
     */
    @RequestMapping("/toQueryOrderDetail/{oid}")
    public ModelAndView queryOrderDetail(@PathVariable("oid") String oid) {
        Order order = orderService.getOrderDetail(oid);
        ModelAndView mv = new ModelAndView();
        mv.addObject("order", order);
        mv.setViewName("orderDetails");
        return mv;
    }

    /**
     * 退保 提交申请
     *
     * @return
     */
    @RequestMapping("/updateOstate")
    public Result updateOstate(Order order) {
        boolean flag = orderService.updateOstate(order);
        if (flag){
            result.setMessage("success");
        }else{
            result.setMessage("false");
        }
        return result;
    }

    @RequestMapping("/getUserByIdCard")
    public Result getUserByIdCard(String idcard){
        User user=orderService.getUserByIdCard(idcard);
        if (user!=null){
            ////已存在客户信息 在存在时直接调用该用户的suId
            result.setMessage(user.getSuId());
        }else{
            /////没有客户信息   需要先输入客户的信息后才能 购买保险
            result.setMessage("false");
        }
        return result;
    }

    /**
     * 根据车牌号查询车辆的信息是否已经存在系统中
     * @param licensenum
     * @return
     */
    @RequestMapping("/getCarsByLicensenum")
    public Result getCarsByLicensenum(String licensenum){
        Cars cars=orderService.getCarsByLicensenum(licensenum);
        if (cars!=null){
            result.setMessage(cars.getCarUuid());
        }else{
            result.setMessage("false");
        }
        return result;
    }
    /**
     * 查询所有的保险套餐
     * @return
     */
    @RequestMapping("/getAllCombo")
    public List<Combo> getAllCombo(){
        return orderService.getAllCombo();
    }

    /**
     * 根据uuid查询订单的详细信息并携带数据  跳转页面
     * @param ouid
     * @return
     */
    @RequestMapping("/getOrderByOuid")
    public ModelAndView getOrderByOuid(String ouid){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("orderrenew");
        Order order=orderService.getOrderByOuid(ouid);
        mv.addObject("order",order);
        return mv;
    }


    /**
     * 根据uuid查询订单的详细信息  并携带数据  跳转页面
     * @param ouid
     * @return
     */
    @RequestMapping("/getOrderByOuid2")
    public ModelAndView getOrderByOuid2(String ouid){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("ordertopay");
        Order order=orderService.getOrderByOuid(ouid);
        mv.addObject("order",order);
        return mv;
    }

    /**
     * 缴费
     * @param order
     * @param uid
     * @param caruid
     * @param comuuid
     * @param session
     * @return
     */
    @RequestMapping("/updatePaystate")
    @ResponseBody
    public boolean updatePaystate(Order order,String uid,String caruid,String comuuid, HttpSession session){
        ////从session中获取当前登录的员工的信息
        Emp emp= (Emp) session.getAttribute("emp");
        order.setEmp(emp);

        User user=new User();
        user.setSuId(uid);
        order.setUser(user);

        Cars cars=new Cars();
        cars.setCarUuid(caruid);
        order.setCars(cars);

        Combo combo=new Combo();
        combo.setComuuid(comuuid);
        order.setCombo(combo);
        boolean flag = orderService.updateOrderPaystate(order);
        return flag;
    }

    /**
     * 关闭订单
     * @param order
     * @return
     */
    @RequestMapping("/closeOrder")
    public boolean closeOrder(Order order){
        return orderService.updateOrderStatus(order);
    }
    /////导出excel

    @RequestMapping("/export")
    public @ResponseBody
    String export(HttpServletResponse response){
        response.setContentType("text/html;charset=UTF-8");
        try {
            ServletOutputStream out=response.getOutputStream();
            String fileName=new String(("baodan").getBytes(),"UTF-8");
            response.setHeader("Content-disposition","attachment;fileName="+fileName+".xls");
            String[] titles={"保单号","客户名称","联系方式","车牌号","加保时间","是否缴费","支付方式","操作员","套餐类型","订单状态","备注"};
            orderService.export(titles,out);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "fail";
        }
    }
    @RequestMapping("/getCarsByUser")
    public List<Cars> getCarsByUser(String suId){
        List<Cars> carsList=orderService.getCarByUser(suId);
        return carsList;
    }

    /**
     * 获取当前套餐的价格
     * @param
     * @return
     */
    @RequestMapping("/getComboPrice")
    public double getComPrice(String comuuid, String licensenum){
        return orderService.getCombPrice(comuuid,licensenum);
    }

    @RequestMapping("/orderInfo")
    public Map<String,Object> getOrderInfoByCarLicenseNum(String licenseNum){
        Map<String,Object> map=new HashMap<String,Object>();
        List<Order> list=new ArrayList<Order>();
        Order o=orderService.getOrderInfoByCarLicenseNum(licenseNum);
        List<Insurcate> insurcateList=null;
        if(o!=null) {
            list.add(o);
            Double rate=orderService.getRateByCarPrice(o.getCars().getPrice());
            insurcateList=insurcateService.getInsurcateByComuuid(o.getCombo().getComuuid());
            map.put("rate",rate);
            map.put("insurcateList",insurcateList);
        }
        map.put("orderList",list);
        return map;
    }








    public ComboService getComboService() {
        return comboService;
    }

    public void setComboService(ComboService comboService) {
        this.comboService = comboService;
    }

    public OrderService getOrderService() {
        return orderService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public InsurcateService getInsurcateService() {
        return insurcateService;
    }

    public void setInsurcateService(InsurcateService insurcateService) {
        this.insurcateService = insurcateService;
    }
}
